package xjhttputil

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"unsafe"
)

// 基本get请求
func BasicGet(url string) (string, error) {
	resp, err := http.Get(url)
	if err != nil {
		log.Println(err.Error())
		return "", err
	}
	defer resp.Body.Close()
	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Println(err.Error())
		return "", err
	}
	return (string(b)), nil
}

func Get(url, token string) (string, error) {
	reader := bytes.NewReader(nil)
	request, err := http.NewRequest("GET", url, reader)
	defer request.Body.Close() //程序在使用完回复后必须关闭回复的主体
	if err != nil {
		return "", err
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	//必须设定该参数,POST参数才能正常提交，意思是以json串提交数据
	if token != ""{
		request.Header.Set("Authorization", token)
	}

	client := http.Client{}
	resp, err := client.Do(request) //Do 方法发送请求，返回 HTTP 回复
	if err != nil {
		return "", err
	}

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {		
		return "", err
	}

	//byte数组直接转成string，优化内存
	str := (*string)(unsafe.Pointer(&respBytes))
	return *str, nil
}

func Post(url, token string, data interface{}) (string, error) {
	bytesData, err := json.Marshal(data)
	if err != nil {
		return "", err
	}

	reader := bytes.NewReader(bytesData)

	request, err := http.NewRequest("POST", url, reader)
	defer request.Body.Close() //程序在使用完回复后必须关闭回复的主体
	if err != nil {
		return "", err
	}
	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
	//必须设定该参数,POST参数才能正常提交，意思是以json串提交数据
	if token != ""{
		request.Header.Set("Authorization", token)
	}

	client := http.Client{}
	resp, err := client.Do(request) //Do 方法发送请求，返回 HTTP 回复
	if err != nil {
		return "", err
	}

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {		
		return "", err
	}

	//byte数组直接转成string，优化内存
	str := (*string)(unsafe.Pointer(&respBytes))
	return *str, nil
}